% correct objective IR power transmission factor
% hyzhou, 11/21/2017
% axis specifies whether the coordinate system si defined in green or in IR
% coordinates
function fac_obj = get_ir_factor(vx, vy, axis)

if strcmp(axis,'green')
    temp_filename = 'Green_Infrared_Calibration.txt';
    temp_path = 'C:\jmaze\matlab\Experiment\Sets\';
    fid = fopen([temp_path temp_filename],'r');
    Transf_factors = fscanf(fid,'%f',[4,1]);
    fclose(fid);
    
    Ang = Transf_factors(1);
    Scale = Transf_factors(2);
    Off_Vx = Transf_factors(3);
    Off_Vy = Transf_factors(4);
    
    Ang = Ang/180*pi;
    R = [cos(Ang) -sin(Ang); sin(Ang) cos(Ang)]*Scale;
    D = [Off_Vx; Off_Vy];
    
    for i = 1:size(vx,1)*size(vx,2)
        % input coordinate in APD
        Pos_APD = [vx(i); vy(i)];
        
        % X = - R*(P-D) --> P = -inv(R)*X + D;
        Pos_PD = -inv(R)*Pos_APD + D;
        vx(i) = Pos_PD(1);
        vy(i) = Pos_PD(2);
    end
end

ir_file_name = 'C:\Users\WormSetup\Dropbox\SharedFlies\WormProject\WormData\PowerCalibration\IR_power_2018-08-30.csv';
calib_ir = csvread(ir_file_name,2);
calib_ir = calib_ir(:,1:3);
[x_ir,y_ir] = meshgrid(-2.1:0.05:2.1);

fac_obj = griddata(calib_ir(:,1),calib_ir(:,2),calib_ir(:,3),vx,vy,'natural');
normT = max(max(fac_obj));

fac_obj = fac_obj./normT;


